//
//  HYGameInfoViewController.m
//  HaiYue
//
//  Created by skyline on 2017/12/29.
//  Copyright © 2017年 skyline. All rights reserved.
//

#import "HYGameInfoViewController.h"
#import "HYReplyViewController.h"
#import "HYGameInfoHeaderView.h"
#import "HYGameInfoDetailCell.h"
#import "HYGameInfoCommentCell.h"
#import "HYGameInfoServerCell.h"
#import "HYGameInfoGiftCell.h"
#import "HYGameInfoTradeCell.h"
#import "HYToolBar.h"
#import "HYGameDetailModel.h"
#import "HYCommentModel.h"
#include <objc/runtime.h>
@interface HYGameInfoViewController ()<HYToolBarDelegate,UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) HYGameInfoHeaderView *headerView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) HYToolBar *toolBar;
@property (nonatomic, strong) HYGameDetailModel *model;
//@property (nonatomic, assign) CGFloat cellH;


@property (nonatomic, strong) HYCommentList*commentList;
@end

@implementation HYGameInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.toolBar.hidden = NO;
    self.title = @"游戏详情";
    // Do any additional setup after loading the view.
}

- (HYGameInfoHeaderView *)headerView
{
    if (!_headerView)
    {
        _headerView = [[HYGameInfoHeaderView alloc] init];
        [_headerView addTarget:self action:@selector(actionForHeaderSelect) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_headerView];
        [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.height.mas_equalTo(CGRectGetHeight(self.headerView.bounds));
            make.left.equalTo(self.view).with.offset(0);
            make.right.equalTo(self.view);
        }];
    }
    return _headerView;
}

- (HYToolBar *)toolBar
{
    if (!_toolBar)
    {
        _toolBar = [[HYToolBar alloc]initWithMiddleTitle:@"安装" leftTitle:@"客服" leftImageName:@"helpcenter_qq_normal" rightTitle:@"点评" rightImageName:@"title_pinglun_iv"];
        _toolBar.titleColor = THEME_COLOR;
        _toolBar.delegate = self;
        [self.view addSubview:_toolBar];
        [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.height.mas_equalTo(self.toolBar.bounds.size.height);
        }];
    }
    return _toolBar;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[self customLayout]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.bounces = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[HYGameInfoDetailCell class] forCellWithReuseIdentifier:@"HYGameInfoDetailCell"];
        [_collectionView registerClass:[HYGameInfoCommentCell class] forCellWithReuseIdentifier:@"HYGameInfoCommentCell"];
        [_collectionView registerClass:[HYGameInfoServerCell class] forCellWithReuseIdentifier:@"HYGameInfoServerCell"];
        [_collectionView registerClass:[HYGameInfoGiftCell class] forCellWithReuseIdentifier:@"HYGameInfoGiftCell"];
        [_collectionView registerClass:[HYGameInfoTradeCell class] forCellWithReuseIdentifier:@"HYGameInfoTradeCell"];
        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.headerView.mas_bottom);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.toolBar.mas_top);
        }];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)customLayout
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(SCREEN_MIN_LENGTH, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - HYToolBarHeight - CGRectGetHeight(self.headerView.bounds));
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsZero;
    layout.minimumLineSpacing = 0.0;
    return layout;
}

- (void)setModel:(HYGameDetailModel *)model
{
    if (_model != model)
    {
        _model = model;
        self.headerView.model = model;
        [self.collectionView reloadData];
    }
}

- (void)actionForHeaderSelect
{
    
    if (_headerView.seg.selectedSegmentIndex == 0)
    {
        
    }
    else if (_headerView.seg.selectedSegmentIndex == 1)
    {
        //        [self requesthttpsComment];
    }
    else if (_headerView.seg.selectedSegmentIndex == 2)
    {
        
    }
    else if (_headerView.seg.selectedSegmentIndex == 3)
    {
        
    }
    else if (_headerView.seg.selectedSegmentIndex == 4)
    {
        
    }
    NSLog(@"选中。%ld",_headerView.seg.selectedSegmentIndex);
    [self.collectionView setContentOffset:CGPointMake(SCREEN_MIN_LENGTH * self.headerView.seg.selectedSegmentIndex, 0) animated:YES];
}

- (void)actionForCommentCellRefresh:(NSNotification *)notify
{
    [self requesthttpsComment:nil];
}
- (void)selectoractionForCommentCellMore:(NSNotification *)notify
{
    if (self.commentList.more)
        [self requesthttpsComment:self.commentList.more];
}
//点赞/踩/回复
//1点赞 0 取消 -1踩int commentid = getParaToInt("commentid",0);
//int val = getParaToInt("val",0);//ConstantApp._state_do;
- (void)actionForZanCaiReply:(NSNotification *)notify
{
    if ([notify.name hasSuffix:HYInfoCommentCellReply])
    {
        HYReplyViewController *vc = [[HYReplyViewController alloc] init];
        vc.model = [notify.userInfo valueForKey:@"obj"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        [CCHttp post:API_COMMENT_LIKE para:notify.userInfo success:^(id  _Nonnull response) {
            if ([[response valueForKey:@"retcode"] intValue] == 100 && [[response valueForKey:@"state"] hasPrefix:@"success"])
                [CCNotice post:HYInfoCommentCellCallBack obj:notify.object info:notify.userInfo];
            else
                [CCAlert showMessage:[response valueForKey:@"state"] hidden:nil];
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"error  ----- %@",error.localizedDescription);
        }];
    }
}

#pragma mark -  UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.headerView.seg.numberOfSegments;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        HYGameInfoDetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYGameInfoDetailCell" forIndexPath:indexPath];
        cell.model = self.model;
        return cell;
    }
    else if (indexPath.row == 1)
    {
        HYGameInfoCommentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYGameInfoCommentCell" forIndexPath:indexPath];
        cell.list = self.commentList;
        return cell;
    }
    else if (indexPath.row == 2)
    {
        HYGameInfoServerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYGameInfoServerCell" forIndexPath:indexPath];
        cell.serverlist = self.model.serverlist;
        return cell;
    }
    else if (indexPath.row == 3)
    {
        HYGameInfoGiftCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYGameInfoGiftCell" forIndexPath:indexPath];
        return cell;
    }
    else if (indexPath.row == 4)
    {
        HYGameInfoTradeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HYGameInfoTradeCell" forIndexPath:indexPath];
        return cell;
    }
    return nil;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.headerView.seg.selectedSegmentIndex = scrollView.contentOffset.x / SCREEN_MIN_LENGTH;
}

#pragma mark - UITableViewDelegate
- (void)eventWithClicked:(HYToolBarEvent)event
{
    if (event == HYToolBarEventLeftBtnAction)
    {
        [AppDelegate openQQ];
    }
    else if (event == HYToolBarEventMiddleBtnAction)
    {
        //        itms-services://?action=download-manifest&url=https://dl.ddgame37.com/download/app/ddlxj/ddlxj.plist
        //        itms-services://?action=download-manifest&url=https://dl.ddgame37.com/download/app/yhxy/yhxy.plist
//        [AppDelegate openAPP:@"itms-services://?action=download-manifest&url=https://dl.ddgame37.com/download/app/ddlxj/ddlxj.plist"];
        [AppDelegate openAPP:@"https://itunes.apple.com/cn/app/魔域手游-史诗级魔幻动作手游巨作/id1116552647"];
        //        [AppDelegate openAPP:@"weixin://"];
        //
        //        NSDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[[NSBundle mainBundle]infoDictionary]];
        //
        ////       NSString *path = [[NSBundle mainBundle] pathForResource:@"info" ofType:@"plist"];
        //       NSArray *arr = [dict valueForKey:@"LSApplicationQueriesSchemes"];
        //       NSMutableArray *newarr = [NSMutableArray arrayWithArray:arr];
        //        [newarr addObject:@"mqq"];
        //        [dict setValue:newarr forKey:@"LSApplicationQueriesSchemes"];
        //
        //        [[NSBundle mainBundle] setValue:[dict json] forKey:@"infoDictionary"];
        //        NSLog(@"dict %@",[[[NSBundle mainBundle]infoDictionary] valueForKey:@"LSApplicationQueriesSchemes"]);
        //        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq"]])
        //        {
        //            [CCAlert showMessage:@"可以打开qq" title:nil enter:nil];
        //        }
    }
    else
    {
        id vc = nil;
        if ([[HYUserManager manager].user.accesstoken length] < 1)
        {
            vc = [NSClassFromString(@"HYLoginViewController") new];
        }
        else
        {
            vc = [NSClassFromString(@"HYFeedBackViewController") new];
            [vc setValue:@"评论" forKeyPath:@"title"];
            [vc setValue:API_DO_COMMENT forKey:@"api"];
            [vc setValue:self.model.gameid forKey:@"gameid"];
            [vc setValue:@"提交评论" forKeyPath:@"buttonTitle"];
            [vc setValue:@"请自觉遵守互联网法律法规，文明发言..." forKeyPath:@"textView.placholder"];
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)request
{
    [self startHUD];
    [CCHttp post:API_GAME_DETAIL para:@{@"gameid":self.gameid} success:^(id  _Nonnull response) {
        [self endHUD];
        self.model = [HYGameDetailModel mj_objectWithKeyValues:response];
    } fail:^(NSError * _Nonnull error) {
        [self endHUD];
    }];
}
- (void)requesthttpsComment:(NSString *)more
{
    NSString * api = more?more:API_ARTICLE_COMMENT;
    
    [CCHttp post:api para:@{@"gameid":self.gameid} success:^(id  _Nonnull response) {
        if (!more)
            self.commentList = [HYCommentList mj_objectWithKeyValues:response];
        else
        {
            HYCommentList *newlist = [HYCommentList mj_objectWithKeyValues:response];
            NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.commentList.list];
            [tempArr addObjectsFromArray:newlist.list];
            newlist.list = tempArr;
            self.commentList = newlist;
        }
        [CCNotice post:CCNoticeHYGameInfoCommentCellList obj:nil info:@{@"list":self.commentList}];
    } fail:^(NSError * _Nonnull error) {
        
    }];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.style = HYViewNaviBarStyleOnlyLeftBtn;
    
    [CCNotice addObs:self sel:@selector(actionForZanCaiReply:) name:HYInfoCommentCellZan obj:nil];
    [CCNotice addObs:self sel:@selector(actionForZanCaiReply:) name:HYInfoCommentCellCai obj:nil];
    [CCNotice addObs:self sel:@selector(actionForZanCaiReply:) name:HYInfoCommentCellReply obj:nil];
    [CCNotice addObs:self sel:@selector(actionForCommentCellRefresh:) name:HYGameInfoCommentCellRefresh obj:nil];
    [CCNotice addObs:self sel:@selector(selectoractionForCommentCellMore:) name:HYGameInfoCommentCellMore obj:nil];

    [self request];
    [self requesthttpsComment:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [CCNotice rmObs:self name:HYInfoCommentCellCai obj:nil];
    [CCNotice rmObs:self name:HYInfoCommentCellZan obj:nil];
    [CCNotice rmObs:self name:HYInfoCommentCellReply obj:nil];
    [CCNotice rmObs:self name:HYGameInfoCommentCellRefresh obj:nil];
    [CCNotice rmObs:self name:HYGameInfoCommentCellMore obj:nil];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
